﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

namespace ClipperHouse.jQuery.Base
{
	public class JQueryExpression
	{
		public JQueryExpression()
		{
			this.Params = new NameValueCollection();
			this.Indent = 0;
		}

		public string Selector
		{
			get;
			set;
		}

		public SelectorPrefix SelectorPrefix
		{
			get;
			set;
		}

		public string Method
		{
			get;
			set;
		}

		public NameValueCollection Params
		{
			get;
			set;
		}

		protected string ParamsExpression
		{
			get
			{
				string paramsExpression = String.Empty;

				List<string> paramsKeys = this.Params.AllKeys.ToList();

				string paramDelimiter = ", ";

				foreach (string paramKey in paramsKeys)
				{
					string paramExpression = String.Empty;

					if (this.Params[paramKey] != null && !String.IsNullOrEmpty(this.Params[paramKey].ToString()))
					{
						string paramAsString = this.Params[paramKey].ToString().Trim();

						paramExpression = paramAsString.ToJSParam();

						paramsExpression += paramExpression;
						paramsExpression += paramDelimiter;
					}
				}

				if (paramsExpression.EndsWith(paramDelimiter))
				{
					paramsExpression = paramsExpression.Substring(0, paramsExpression.Length - paramDelimiter.Length);
				}

				return paramsExpression;
			}
		}

		public string Javascript
		{
			get
			{
				string result = String.Empty;

				if (!IsChain)
				{
					result += Utility.Indent(this.Indent) + this.SelectorPrefix.ToSelectorString();
				}

				if (!String.IsNullOrEmpty(this.Selector))
				{
					string selectorExpr = "(\"" + this.Selector + "\")";
					bool isReserved = reservedSelectors.Contains(this.Selector);

					if (isReserved)
					{
						selectorExpr = selectorExpr.Replace("\"", "");	// remove quotes
					}

					result += selectorExpr;
				}

				if (!String.IsNullOrEmpty(this.Method))
				{
					string methodCall = "." + this.Method;

					methodCall += "(" + this.ParamsExpression + ")";

					if (!String.IsNullOrEmpty(methodCall))
					{
						if (IsChain)
						{
							methodCall = Environment.NewLine + Utility.Indent(this.Indent) + methodCall;
						}

						result = result + methodCall;
					}
				}

				if (IsEnd)
				{
					result += "; ";
				}
				return result;
			}
		}

		public int Indent
		{
			get;
			set;
		}

		public bool IsChain
		{
			get;
			set;
		}

		public bool IsEnd
		{
			get;
			set;
		}

		protected List<String> reservedSelectors = new List<string> { "this", "window", "document", "body", "document.body" };
	}
}
